package com.whccb.apps.office.document.button;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.actionsoft.bpms.bpmn.engine.core.delegate.ProcessExecutionContext;
import com.actionsoft.bpms.bpmn.engine.listener.ValueListener;
import com.actionsoft.bpms.commons.database.RowMapper;
import com.actionsoft.bpms.commons.htmlframework.HtmlPageTemplate;
import com.actionsoft.bpms.util.DBSql;
import com.whccb.apps.office.document.ODConstant;
import com.whccb.apps.office.document.util.ODAppUtil;

public class ChoseOfficeDocumentTypeButton extends ValueListener {

	@Override
	public String execute(ProcessExecutionContext ctx) throws Exception {
		// 通过帐号查询可访问的文种列表
		String inWhere = ODAppUtil.getUserDeptSqlInWhere(null, ctx
				.getUserContext().getDepartmentModel().getId());

		String querySql = " SELECT * FROM BO_WHBK_OD_RECORDTYPE WHERE USESCOPEID in "
				+ inWhere;
		List<Map<String, String>> odRecordTypeBoList = DBSql.query(querySql,
				new RowMapper<Map<String, String>>() {
					@Override
					public Map<String, String> mapRow(ResultSet rs, int rowNum)
							throws SQLException {
						Map<String, String> map = new HashMap<String, String>();
						map.put("ID", rs.getString("ID"));
						map.put("CODE", rs.getString("CODE"));
						map.put("NAME", rs.getString("NAME"));
						return map;
					}
				});

		JSONArray jsons = new JSONArray();
		if (odRecordTypeBoList != null && !odRecordTypeBoList.isEmpty()
				&& odRecordTypeBoList.size() > 0) {
			for (Map<String, String> map : odRecordTypeBoList) {
				if (map != null && !map.isEmpty()) {
					JSONObject json = new JSONObject();
					json.put("ID", map.get("ID"));
					json.put("CODE", map.get("CODE"));
					json.put("NAME", map.get("NAME"));
					jsons.add(json);
				}
			}
		}
		JSONObject typeList = new JSONObject();
		typeList.put("typeList", jsons);
		JSONObject typeDataJson = new JSONObject();
		typeDataJson.put("data", typeList);

		Map<String, Object> macroLibraries = new HashMap<String, Object>();
		macroLibraries.put("sid", ctx.getUserContext().getSessionId());
		macroLibraries.put("typeJson", typeDataJson);
		return HtmlPageTemplate.merge(ODConstant.APP_ID, "gw.wz.html",
				macroLibraries);
	}
}
